#!/usr/bin/perl -w
#-----------------------------------------------------------+
#                                                           |
# JaniDir.pl                                                |
#                                                           |
#-----------------------------------------------------------+
#                                                           |
#  AUTHOR: James Estill                                     |
# CONTACT: JamesEstill_at_gmail.com                         |
# STARTED: 1/18/2005                                        |
# UPDATED: 2/23/2005                                        |
#   ABOUT: The janidir subfunction will clean up dirs of    | 
#          files that are past their shelf life as measured |   
#          in days.                                         |
#                                                           |
#-----------------------------------------------------------+

=head1 NAME

JaniDir.pl - Directory cleaning

=head1 SYNOPSIS

   JaniDir.pl -e DaysToExpire -d DirToClean -l LogFile -q

=head1 DESCRIPTION

The janidir subfunction will clean up dirs of
files that are past their shelf life as measured
in days.

=head1 ARGUMENTS

=over 2

=item -e DaysToExpire

The tolerated age of a file measured in days. Files past this
age will be deleted from the directory.

=item -d DirToClean

The full path of the directory that will be cleaned.

=item -l LogFile

The full path to the log file. This file documents the files that 
were deleted by JaniDir. New information will be appended to
an existing file.

=item -q

This is the quiet flag. Running the program with the q activated
will not print information to STDOUT. This is the option to use for
cron jobs.

=back

=head1 AUTHOR

James C. Estill E<lt>JamesEstill at gmail.comE<gt>

=cut

# INCLUDES
use Getopt::Std;               # Get command line options


#-----------------------------+
# GET OPTIONS FROM COMMAND    |
# LINE AND LOAD VARIABLES     |
#-----------------------------+
my %Options;                   # Declare the options hash with local scope
getopts('l:e:d:q', \%Options); # Get the options from the command line

# Set variables to the command line options
my $Expiration = $Options{e} || 
    die "You must declare expiration in days with -e \n";
my $Dir2Clean = $Options{d} || 
    die "You must declare the directory with -d\n";
my $Log = $Options{l} || 
    die "You must declare the log file with -l\n";
my $Quiet = $Options{q};
if( $Quiet == 1 ){ 
    $Quiet = "TRUE"}
else{ 
    $Quiet = "FALSE"}

# Test print options
print "Exp: $Expiration\n";
print "Dir $Dir2Clean\n";
print "Log: $Log\n";
print "Qut: $Quiet\n";
exit;

&janidir($Expiration,$Dir2Clean,$Log,$Quiet);

exit;

#-----------------------------------------------------------+
#  SUBFUNCTIONS                                             |
#-----------------------------------------------------------+

# SET SOME VARIABLES AND GET THE TIME
sub janidir
{
  my $ShelfLife = $_[0];    # Shelf life of the file in days
  my $TargetDir = $_[1];    # Full path of the directory to be cleaned
  my $LogFile = $_[2];      # Full path of the log file
  my $NoOutput = $_[3];     # True if a quiet run is preferred, false otherwise
  my $Now = time;
  
  # READ EACH OF THE FILES IN THE TARGET DIR INTO THE FileList Array
  open(LOG, ">>$LogFile")    || die "$LogFile not available\n";   # Open the log file for appending
  opendir( DIR, $TargetDir ) || die "$TargetDir Not Available\n"; # Open the directory
  my @FileList = grep !/^\.\.?$/, readdir DIR ;                   # Read the directory ignoring the . and ..
  closedir( DIR );                                                # Close the directory
  
  chdir $TargetDir;                                               # Change to the target directory
  
  foreach $IndFile(@FileList)
    {
      
      $ModTime = (stat("$IndFile"))[9];                               # Get the time the file was modified
      $Diff = $Now - $ModTime;                                        # Get the difference in seconds
      $DayDiff = (($Diff/60)/60)/24;                                  # Convert raw second diff to day diff
      
      if ($DayDiff > $ShelfLife)                                      # If the file is older than the shelf life
	{                                                             # then
	  $status = "Stale";                                          # it is stale
	  system ("rm $IndFile");                                     # and should be deleted
	}
      else                                                            # otherwise the file is
	{
	  $status = "Fresh";                                          # fresh.
	}
      
      # SHOW THE STATUS OF THE FILES THIS CAN BE PRINTED TO A LOG FILE
      if ($NoOutput eq "FALSE") {
	  print "$IndFile \t $ModTime \t $Diff \t $DayDiff \t $status \n";
      }
      print LOG "$IndFile \t $ModTime \t $Diff \t $DayDiff \t $status \n";  
    }
  
  close (LOG);
}


sub UserFeedback
  {
#
# SUBFUNCTION TO GET USER FEEDBACK
# TO A YES NO QUESTION THAT IS PASSED
# AS A VARIABLE. RETURNS Y or N.
#
      my $Question = $_[0];
      my $Answer;
      
      print "\n$Question \n";
      
      while (<>)
      {
	  chop; # Remove carriage return
	  
	  if ( ($_ eq 'y') || ($_ eq 'Y') || ($_ eq 'yes') || ($_ eq 'YES') )
	  {
	      # If the user says yes
	      $Answer = "Y";
	      return $Answer;
	  }
	  elsif ( ($_ eq 'n') || ($_ eq 'N') || ($_ eq 'NO') || ($_ eq 'no') )  	  {
	      # If the user says no
	      $Answer = "N";
	      return $Answer;
	  }
	  else
	  {
	      print "\n$Question \n";
	  }
      } # End of while getting input from the command line statement
  } # End of subfunction

#-----------------------------------------------------------+
# HISTORY                                                   |
#-----------------------------------------------------------+
# 2/23/2005
#  - Added user inputs for shelf life, Target dir, log file, 
#    and a quiet mode flag
#    -l takes argument: full path of the log file
#    -e takes argument: expiration in number of days
#    -t takes argument: full path of the target dir that 
#       is to be cleaned
#    -q boolean flag: when used sets quiet mode, use this 
#       for cron jobs
#  - Progam dies and prints error messages when it does not 
#    get all the required input from the user
#  - Program dies and prints error message when the target 
#    dir and log file not available
# 
# 04/23/2007
# - Made a few modifications for upload to jperl
#
# 05/01/2007
# - Changed program documentation to POD format.
# - Cleaned the code up a little bit
